import {imageFileChoice} from '@/utils/file-choice'

//检查空对象
export function checkNullObj(obj) {
  //获取所有key
  const keys = Object.keys(obj)
  if (keys.length < 1) return false

  for (const key of keys) {
    //如果为空直接返回
    if (obj[key]?.length < 1) return false

    //如果子项为数组则遍历判断
    if (typeof obj[key] === 'object') {
      if (!checkNullObj(obj[key])) return false
    }
  }

  return true
}

//判断对象内部是否有图片，如果有则对图片对象进行转换
export async function checkImgAndExtract(obj, table) {
  if (typeof obj !== 'object') return

  //获取所有key
  const keys = Object.keys(obj)

  //判断对象
  if (keys.length === 2 && keys.includes('filename') && keys.includes('path')) {
    //判断视频类型
    const vidwoRule = /(\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4))$/i
    const mediaType = vidwoRule.test(obj.filename) ? 'video' : 'images'

    //如果有filename和path则上传云存储并转换对象
    return await imageFileChoice.requestUrl(await imageFileChoice.upload(obj, table, mediaType))
  }

  for (const key of keys) {
    //如果子项为数组则遍历判断
    if (typeof obj[key] === 'object') {
      obj[key] = await checkImgAndExtract(obj[key], table)
    }
  }

  return obj
}
